package yao.common.file;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;


/**
 * 对磁盘文件的读写
 * @author chenyao
 *
 */
public class FileUtils {
	
	/**
	 * 对文件进行添加
	 * @param filePath
	 * @param content
	 */
	public static void append(String filePath, String content) {
		checkArgument(StringUtils.isNotBlank(filePath), "filePath is bank");
		Path path = Paths.get(filePath);
		//这里选择的编码要正确，不然会抛出 java.nio.charset.MalformedInputException: Input length = 1 异常
		try(BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND, StandardOpenOption.CREATE)) {
			writer.append(content);
			writer.newLine();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("write error info error!!!");
		}
	}
	
	/**
	 * 已utf-8方式读取
	 * @param filePath 文件路径
	 * @return list<String> 一行为list的一个item
	 */
	public static List<String> readByUTF8(String filePath) {
		checkArgument(StringUtils.isNotBlank(filePath), "filePath is bank");
		Path path = Paths.get(filePath);		
		return readByUTF8(path);
	}
	
	/**
	 * 已utf-8方式读取
	 * @param filePath 文件路径
	 * @return list<String> 一行为list的一个item
	 */
	public static List<String> readByUTF8(Path path) {
		checkNotNull(path);
		List<String> result = new ArrayList<String>();
		try(BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
			String line;
			while((line = reader.readLine()) != null && StringUtils.isNotBlank(line)) {
				result.add(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return result;
	}
	
}
